//
//  SLHomeVC.swift
//  sulit-loan
//
//  Created by 王刚锋 on 2025/4/5.
//  Copyright © 2025 coolBoy. All rights reserved.
//

import UIKit
import SwiftyJSON
import AdSupport
import Kingfisher
import CoreLocation
import CoreTelephony
import MBProgressHUD
class SLHomeVC: SLTableVC<Any> {
    var data: SLHomeModel?
    var articleA: JSON?
    var articleB: SLHomeListModel?
    var articleC: SLHomeListModel?
    var articleD: [JSON] = []

    var type: Int = 0 //1大卡 2小卡

    var msgIndex:Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableview.mj_header?.alpha = 0
        self.tableview.rowHeight = 95
        self.tableview.emptyDataSetSource = nil
        self.tableview.emptyDataSetDelegate = nil
        self.tableview.mj_footer = nil
        let titleL = create_imageView(image: IMAGE("文本"), mode: .scaleToFill, supView: self.view) { make in
            make.left.equalTo(24)
            make.top.equalTo(DevConfig.state_height+32)
            make.width.equalTo(180)
            make.height.equalTo(105)
        }
        self.backgroundImageV.image = IMAGE("Home_BG")
        self.tableview.snp.removeConstraints()
        self.tableview.snp.remakeConstraints { make in
            make.left.right.top.equalTo(0)
            make.bottom.equalTo(-49)
        }
        self.tableview.contentInset = .init(top: 118+DevConfig.nav_height, left: 0, bottom: 0, right: 0)
        self.tableview.register(SLHomeListCell.self, forCellReuseIdentifier: "SLHomeListCell")
        self.view.bringSubviewToFront(self.tableview)
    }
    func updateUI(){
        if let data = self.articleB {
            self.bigPicture()
            self.msgIndex = 0
            self.datas = []
            self.tableview.reloadData()
           
        }
        if let data = self.articleC{
            self.littlePicture()
            self.datas = articleD
            self.tableview.reloadData()
        }
    }
    @objc func msgScrollAction(){
   
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.refreshAction()
    }
    override func refreshData(isPullDown: Bool = true) {
        self.tableview.mj_footer?.endRefreshing()
        self.tableview.mj_header?.endRefreshing()
        self.tableview.mj_header?.alpha = 0
        SLHttpTool.AsyncReportData(path: "/satisfies/tufts", target: self) { responseCall, success, msg, code in
            self.data = SLHomeModel.init(json: responseCall["wavelets"])

            if let arr = self.data?.quite{
                for json in arr{
                    if let went = json["went"].arrayValue.first{
                        if json["transfer"] == "neolithica"{
                            self.articleA = went
                        }else if json["transfer"] == "neolithicb"{
                            self.type = 1
                            self.articleB = SLHomeListModel.deserialize(from: went.dictionary)
                            self.articleC = nil
                        }else if json["transfer"] == "neolithicc"{
                            self.type = 2
                            self.articleB = nil
                            self.articleC = SLHomeListModel.deserialize(from: went.dictionary)
                        }else if json["transfer"] == "neolithicd"{
                            self.articleD = json["went"].arrayValue
                        }
                    }
                }
            }
            self.updateUI()
            self.upload()
            self.checkLocationServices()
        }
    }
    func bigPicture(){
        self.listHeadView.isHidden = true
        self.headView.isHidden = false
        self.headView.setMsg(messageArr:self.data!.probable)
        self.tableview.tableHeaderView = self.headView
//        self.pageControl.numberOfPages = 2
        self.tableview.backgroundColor = .clear
//        self.pageView.reloadData()
        if let model = articleB{
//            self.headView.topLabel.text = model.singularly
            self.headView.numL.text = model.evolution
            self.headView.numbL.text = model.james
            self.headView.button.setTitle(model.civilizations, for: .normal)
            self.headView.button.layer.cornerRadius = 22
        }

   
    }
    func littlePicture(){
        self.headView.isHidden = true
        self.listHeadView.isHidden = false
        self.tableview.tableHeaderView = self.listHeadView
        self.tableview.backgroundColor = .clear
        if let model = articleC{
            self.listHeadView.numL.text = model.evolution
            self.listHeadView.numaL.text = model.handbook
            self.listHeadView.numbL.text = model.james
            self.listHeadView.titleaL.text = model.illustrated
            self.listHeadView.titlebL.text = model.suggests
            self.listHeadView.button.setTitle(model.civilizations, for: .normal)
            self.listHeadView.button.layer.cornerRadius = 22
        }
    }
    @objc func buttonClick(btn: UIButton){
        var sources: String = ""
        if btn == self.headView.buttonA{
            sources = self.articleB!.lycia
        }else if btn == self.listHeadView.buttonA{
            sources = self.articleC!.lycia
        }
        zhunru(sources: sources)

    }
    func zhunru(sources: String){
        let mbp = MBProgressHUD.showMessage(message: "")
        SLHttpTool.AsyncReportData(path: "/satisfies/hand",params: ["sources":sources], target: self) { responseCall, success, msg, code in
            mbp.hide(animated: false)
            if code == "0" {
                let string = responseCall["wavelets"]["imitate"].stringValue
                jump(url: string)
                
            }
            
        }
    }

    lazy var listHeadView:SLHomeHeadLittleView = {
        let headView = kLoadXib(xibName: "SLHomeHeadLittleView") as! SLHomeHeadLittleView
        headView.frame = CGRectMake(0, 0, DevConfig.width, devWidthRatio*200)
        headView.buttonA.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
        return headView
    }()
    lazy var headView:SLHomeHeadBigView = {
        let headView = kLoadXib(xibName: "SLHomeHeadBigView") as! SLHomeHeadBigView
        headView.frame = CGRectMake(0, 0, DevConfig.width, 226+(DevConfig.width-30)/345 * 386)
        headView.buttonA.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
        let tapa = UITapGestureRecognizer(target: self, action: #selector(tapClick))
        let tapb = UITapGestureRecognizer(target: self, action: #selector(tapClick))
        headView.agreementV.isUserInteractionEnabled = true
        headView.agreementV.addGestureRecognizer(tapa)
        headView.serviceV.isUserInteractionEnabled = true
        headView.serviceV.addGestureRecognizer(tapb)
        return headView
    }()
    @objc func tapClick(tap:UITapGestureRecognizer){

       if tap.view == self.headView.agreementV {
           let url = __valueForKey(key: KProtocol)
           jump(url: url as? String)
           
        }else if tap.view == self.headView.serviceV {
            let url = self.data?.greece["masarh"].stringValue
            jump(url: url!)
        }
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return self.datas.count
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SLHomeListCell", for: indexPath) as! SLHomeListCell
        let json = self.articleD[indexPath.section]
        cell.icon.kf.setImage(with: URL(string: json["commented"].stringValue))
        cell.titleLabel.text = json["singularly"].stringValue
        cell.amountLabel.text = json["evolution"].stringValue
        cell.rateLabel.text = "(\(json["artefacts"].stringValue))"
        cell.dayLabel.text = json["handbook"].stringValue
        cell.applyButton.setTitle(json["civilizations"].stringValue, for: .normal)
        return cell
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    
        return 12
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 95
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let json = self.articleD[indexPath.section]
        zhunru(sources: json["lycia"].stringValue)
        
    }
    func upload(){
        self.locationManager.startUpdatingLocation()
        let idfa = SLKeychain.getIDFA()
        let idfv = SLKeychain.getIDFV()
        let params:[String: String] = ["buddharupa":idfv,
                                       "suggested":idfa]
        SLHttpTool.AsyncPointData(path: "/satisfies/quite",params: params, target: self) { responseCall, success, msg, code in
            
        }
        uploadData()
    }

    func uploadData(){
        var cob:[String: String] = [:]
        var lopburi:[String: String] = [:]
        var sukhothai:[String: String] = [:]
        var complexes:[String: String] = [:]
        var prangs:[String: String] = [:]
        var sumatra:[String: Any] = [:]
        cob["corn"] = Helper.getNewFreeSize()
        cob["measure"] = Helper.getTotalDiskSize()
        cob["arun"] = Helper.getTotalMemorySize()
        cob["bangkok"] = Helper.getAvailableMemorySize()
        
        lopburi["categories"] = SLTool.getDeviceBatteryLevel()
        lopburi["falls"] = SLTool.getDeviceBatterySratus()
        
        sukhothai["masters"] = SLTool.getDeviceSystemVersion()
        sukhothai["collapsed"] = SLTool.getDeviceModel()
        sukhothai["thom"] = SLTool.getDeviceName()

        complexes["rekha"] = "0"
        complexes["resembled"] = "0"
        if SLTool.isJailBroken(){
            complexes["resembled"] = "1"
        }

        let timeZone = TimeZone.current
        prangs["inclusion"] = timeZone.identifier
        prangs["buddharupa"] = SLKeychain.getIDFV()
        prangs["fifth"] = Locale.current.languageCode
        prangs["chaiwatthanaram"] = SLTool.getNetworkType()
        prangs["suggested"] = SLKeychain.getIDFA()
        
        var mon:[String:Any] = [:]
        if let wifiInfo = SLTool.getCurrentWiFiInfo(){
            mon["funan"] = wifiInfo.BSSID
            mon["suthat"] = wifiInfo.SSID
        }else{
            
        }
        sumatra["mon"] = mon

        var params:[String:Any] = [:]
        params["cob"] = cob
        params["lopburi"] = lopburi
        params["sukhothai"] = sukhothai
        params["complexes"] = complexes
        params["prangs"] = prangs
        params["sumatra"] = sumatra
        if let jsonData = try? JSONSerialization.data(withJSONObject: params, options: []) {
            if let jsonString = String(data: jsonData, encoding: .utf8) {
                SLHttpTool.AsyncPointData(path: "/satisfies/probable",params: ["wavelets":jsonString], target: self) { responseCall, success, msg, code in
                    
                }
            }
        }
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

    }
}
extension SLHomeVC {
// MARK: 位置信息
    override func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = manager.location {
            let geocoder = CLGeocoder()  // 新增地理编码器
            geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
               if error != nil {return}
               if let placemarks = placemarks {
                   let latitude = "\(location.coordinate.latitude)"
                   let longitude = "\(location.coordinate.longitude)"
                   let placemark = placemarks[0]
                   let params:[String:Any] = ["thomas":placemark.locality ?? "",
                                              "ubudiah":placemark.isoCountryCode ?? "",
                                              "neo":placemark.country ?? "",
                                              "malaysia":placemark.thoroughfare ?? "",
                                              "indra":latitude,
                                              "weapon":longitude,
                                              "trishul":placemark.locality ?? "",
                                              "repeated":placemark.subLocality ?? ""]
                   __setValue(value: latitude, key: "latitude")
                   __setValue(value: longitude, key: "longitude")

                   SLHttpTool.AsyncPointData(path: "/satisfies/masarh",params: params, target: self) { responseCall, success, msg, code in
                   }
               }
           }
           // 获取到位置信息后，停止更新位置，节省电量
           manager.stopUpdatingLocation()
       }
       }
}

